package ct.zxd.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ct.zxd.db.Dao;

/**
 * Servlet implementation class HandleFront
 */
public class HandleFront extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;character=utf-8");
        response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
				
		String dish1="",dish2="";
		Dao dao = new Dao();
		String flag = request.getParameter("flag");
		if (flag == null) {
			flag = "";
		}
		
		if (flag.equals("all")) {
			try {
				String idstring = dao.fetchShopPost("1");
				out.write(idstring);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				out.write("获取海报商品失败");
			}
			return;
			
		}
	
		// 上传了新的图片，表单的类型是否为multipart/form-data,如果没有上传图片，这部分代码不会执行
		
		if (ServletFileUpload.isMultipartContent(request)) {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置内存缓冲区的大小,设置为20KB，如果文件大于该设置值,将使用临时文件缓存上传文件 
			factory.setSizeThreshold(1024 * 20);
			
			String dir = request.getSession().getServletContext().getRealPath("/");
			dir =dir.substring(0, dir.length()-9);// "OrderSys\"长度为9
			dir+="ROOT"+File.separator+"front";
			log(dir);
			File file = new File(dir);
			if (!file.exists())file.mkdir();
			
			
			String tempFilePath = dir + File.separator+"temp";
			file = new File(tempFilePath);
			if (!file.exists())file.mkdir();
			// 指定临时文件目录
			factory.setRepository(new File(tempFilePath));
			
			// 构建文件上传对象
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024 * 1024 * 1024);
			
			try {
				List<FileItem> list = upload.parseRequest(request);
				Iterator<FileItem> it = list.iterator();
				// 处理每一个FileItem
				while (it.hasNext()) {
					// 每一个item就代表一个表单输出项
					FileItem item = it.next();
					String formName = item.getFieldName();
					String formValue = item.getString();
					
					if (formValue.isEmpty()) {
						continue;
					}
					if (item.isFormField()) {// 判断input是否为普通表单输入项	
						
						if(formName.equals("postdish1")){
							dish1=formValue;
							dish1 = new String(dish1.getBytes("iso-8859-1"),"utf-8");
						}
						if(formName.equals("postdish2")){
							dish2=formValue;
							dish2 = new String(dish2.getBytes("iso-8859-1"),"utf-8");
						}
						
					} else {
						item.write(new File(dir+File.separator+item.getFieldName()+".jpg"));
					}
				}
			} catch (FileSizeLimitExceededException e) {
				out.print("上传文件大小超过了2MB,重新输入");
				return;
				
				//request.getRequestDispatcher("addadv.jsp?shop="+shop+"&flag="+flag+"&show="+show+"&cateName="+name).forward(request, response);
			} catch (Exception e) {
				out.print("系统出现错误，上传失败,请与管理员联系");
				this.getServletContext().log(e.toString());
			}
		
			
		}else{//如果不是上传了新的图片，则普通方式读取表单，而且不需要使用getBytes("iso-8859-1"),"utf-8")转码
			
			dish1 = request.getParameter("postdish1");
			dish2 = request.getParameter("postdish2");
		}
		
		
		try {
			int count = 0;
			count = dao.updateShopPost(dish1+"-"+dish2);
			String html = "<script language=\"javascript\">location.href='front.jsp?shopid="+'1'+"';</script>";
			if(count>0){
				out.write(html);
			}else{
				out.write("数据库出错");
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
			out.write("服务器连接错误");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
